<?php

namespace app\api\controller;


use app\api\model\GlobalConfig;
use app\api\model\UserList;
use app\api\model\UserWeb;
use ReflectionClass;

class Base extends \app\BaseController
{
    //用户信息
    protected $_global_config;
    protected $_user_info;

    protected $params;

    protected $header;

    /**
     * 初始化
     * @method GET
     */
    public function initialize()
    {
        global $globalConfig;
        $this->crossDomain();
        $this->_global_config = $globalConfig = GlobalConfig::getAllConfig();
        $checkParams = $this->getDocCommentParams(['method', 'needLogin']);
        $this->checkRequestMethod($checkParams['method']);
        $this->params = $this->request->param();
        $this->header = $this->request->header();
        RecordLog(['params' => $this->params, 'headers' => $this->header], request()->controller() . '/' . request()->action());
//        $this->checkRequestParams();
        $this->checkLogin(strtoupper($checkParams['needLogin']) == 'TRUE');
    }

    /**
     * 获取文档设置
     * @param array $params
     * @return array
     */
    private function getDocCommentParams(array $params)
    {
        $className = '\app\api\controller\\' . request()->controller();
        $reflection = new ReflectionClass($className);
        $actions = $reflection->getMethods();
        $data = [];
        foreach ($params as $param) {
            $data[$param] = '';
        }
        foreach ($actions as $action) {
            if ($action->name == request()->action()) {
                $string = $action->getDocComment();
                foreach ($params as $param) {
                    preg_match_all('/@' . $param . '(.*?)[\r\n|\n]/', $string, $arr);
                    $data[$param] = trim($arr[1][0] ?? "");
                }
            }
        }
        return $data;
    }

    /**
     * 请求方式验证
     */
    private function checkRequestMethod($method)
    {
        switch ($method) {
            case 'GET':
                if (!$this->request->isGet())
                    apiReturn(404, '仅支持GET请求');
                break;
            case 'POST':
                if (!$this->request->isPost())
                    apiReturn(404, '仅支持POST请求');
                break;
            case 'PUT':
                if (!$this->request->isPut())
                    apiReturn(404, '仅支持PUT请求');
                break;
            case 'DELETE':
                if (!$this->request->isDelete())
                    apiReturn(404, '仅支持DELETE请求');
                break;
            case 'AJAX':
                if (!$this->request->isAjax())
                    apiReturn(404, '仅支持AJAX请求');
                break;
            case 'MOBILE':
                if (!$this->request->isMobile())
                    apiReturn(404, '仅支持手机请求');
                break;
            default:
                break;
        }
    }

    /**
     * 请求参数验证
     */
    private function checkRequestParams()
    {
        if (in_array(request()->controller() . '/' . request()->action(), ['Common/uploadImage', 'Order/uploadSeatImage', 'Order/saveOrderInfo', 'Order/getChooseGoodsJson'])) return;
        if (!isset($this->header['timestamp']) || !isset($this->header['sign'])) {
            apiReturn(403, '非法请求');
        }
        $this->params['timestamp'] = $this->header['timestamp'];
        ksort($this->params);
        if ($this->params == json_decode(RSAOpensslPKCS8($this->header['sign'], 'decode'), true)) {
            return;
        }
        apiReturn(403, '非法请求');
    }

    /**
     * 检查是否需要登录
     */
    protected function checkLogin($force = true)
    {
        try {
            if (!isset($this->header['token'])) {
                throw new \Exception('请先登录');
            }
            if (empty($this->header['token'])) {
                throw new \Exception('请先登录');
            }
            $auth = aesDecrypt($this->header['token']);
            $token = json_decode($auth, true);
            $userId = $token['user_id'] ?? '';
            if (empty($userId)) {
                throw new \Exception('请先登录');
            }
            if ($token['expire_time'] < time()) {
                throw new \Exception('token已过期');
            }
            $userInfo = UserWeb::find($userId);
            if (!$userInfo) {
                throw new \Exception('请先登录');
            }
            if ($userInfo['user_token'] != $this->header['token'])
                throw new \Exception('token已更新');
            $this->_user_info = $userInfo;
        } catch (\Exception $e) {
            if ($force) apiReturn(101, '用户信息已过期');
        }
    }

    //跨域处理
    protected function crossDomain()
    {
        header('content-type:text/html;charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Token, Origin, X-Requested-With, Content-Type, Accept,timestamp");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
    }

    protected function checkRepeat($name, $uid)
    {
        if (cache($name . '_' . $uid)) {
            apiReturn(199, '重复请求', []);
        }
        cache($name . '_' . $uid, 1, 3);
    }
}